package com.writing.controller;

import com.writing.common.Result;
import com.writing.entity.Novel;
import com.writing.entity.WorldSetting;
import com.writing.service.NovelService;
import com.writing.service.WorldSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 世界观设定Controller
 */
@RestController
@RequestMapping("/novels/{novelId}/world-settings")
public class WorldSettingController {

    @Autowired
    private WorldSettingService worldSettingService;

    @Autowired
    private NovelService novelService;

    /**
     * 验证小说访问权限
     */
    private boolean validateNovelAccess(Long novelId, Long userId) {
        Novel novel = novelService.getNovelDetail(userId, novelId);
        return novel != null;
    }

    /**
     * 获取小说的世界观设定列表
     */
    @GetMapping
    public Result<List<WorldSetting>> getWorldSettings(@PathVariable Long novelId,
                                                      HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            List<WorldSetting> worldSettings = worldSettingService.getWorldSettingsByNovelId(novelId);
            return Result.success(worldSettings);
        } catch (Exception e) {
            return Result.error("获取世界观设定列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取世界观设定详情
     */
    @GetMapping("/{worldSettingId}")
    public Result<WorldSetting> getWorldSetting(@PathVariable Long novelId,
                                               @PathVariable Long worldSettingId,
                                               HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            WorldSetting worldSetting = worldSettingService.getWorldSettingById(worldSettingId, novelId);
            if (worldSetting == null) {
                return Result.error("世界观设定不存在");
            }
            return Result.success(worldSetting);
        } catch (Exception e) {
            return Result.error("获取世界观设定详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建世界观设定
     */
    @PostMapping
    public Result<WorldSetting> createWorldSetting(@PathVariable Long novelId,
                                                  @RequestBody @Valid WorldSetting worldSetting,
                                                  HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            worldSetting.setNovelId(novelId);
            WorldSetting createdWorldSetting = worldSettingService.createWorldSetting(worldSetting);
            return Result.success("创建成功", createdWorldSetting);
        } catch (Exception e) {
            return Result.error("创建世界观设定失败: " + e.getMessage());
        }
    }

    /**
     * 更新世界观设定
     */
    @PutMapping("/{worldSettingId}")
    public Result<WorldSetting> updateWorldSetting(@PathVariable Long novelId,
                                                  @PathVariable Long worldSettingId,
                                                  @RequestBody WorldSetting worldSetting,
                                                  HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            worldSetting.setId(worldSettingId);
            worldSetting.setNovelId(novelId);
            WorldSetting updatedWorldSetting = worldSettingService.updateWorldSetting(worldSetting);
            if (updatedWorldSetting == null) {
                return Result.error("世界观设定不存在或无权限修改");
            }
            return Result.success(updatedWorldSetting);
        } catch (Exception e) {
            return Result.error("更新世界观设定失败: " + e.getMessage());
        }
    }

    /**
     * 删除世界观设定
     */
    @DeleteMapping("/{worldSettingId}")
    public Result<Void> deleteWorldSetting(@PathVariable Long novelId,
                                         @PathVariable Long worldSettingId,
                                         HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            boolean deleted = worldSettingService.deleteWorldSetting(worldSettingId, novelId);
            if (!deleted) {
                return Result.error("世界观设定不存在或无权限删除");
            }
            return Result.success();
        } catch (Exception e) {
            return Result.error("删除世界观设定失败: " + e.getMessage());
        }
    }
}
